package com.example.netty.netty.dubboRPC.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * @Author: 江涛
 * @CreateTime: 2022-09-22  20:54
 * @Description: 完成nettyServer的初始化和启动
 */
public class NettyServer {
    public static void start(String hostName, int port) throws InterruptedException {
        //不同启动方式的选择逻辑（这里忽略，直接调用startServer0）
        startServer0(hostName, port);
    }

    /**
     * 可能有多种不同启动方式
     * @param hostName 地址
     * @param port 端口
     * @throws InterruptedException
     */
    private static void startServer0(String hostName, int port) throws InterruptedException {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(
                            new ChannelInitializer<SocketChannel>() {
                                @Override
                                protected void initChannel(SocketChannel ch) throws Exception {
                                    ch.pipeline().addLast(new StringDecoder())
                                            .addLast(new StringEncoder())
                                            .addLast(new NettyServerHandler());
                                }
                            });
            ChannelFuture future = serverBootstrap.bind(hostName, port).sync();
            System.out.println("服务端启动成功");
            future.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
